package com.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class BioServerSocket {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8090);
        System.out.println("server start... ip:" + serverSocket.getInetAddress().getHostName() + ",port:" + serverSocket.getLocalPort());
        while (true) {
            Socket accept = serverSocket.accept();
            if (accept.isConnected()) {
                System.out.println("accept client ip:" + accept.getRemoteSocketAddress().toString() + ",port:" + accept.getPort());
                Runnable runnable = new Runnable() {
                    Socket client;
                    public Runnable setClient(Socket client) {
                        this.client = client;
                        return this;
                    }
                    @Override
                    public void run() {
                            while (true) {
                                InputStream inputStream = null;
                                try {
                                    inputStream = client.getInputStream();
                                } catch (IOException e) {
                                    if (client.isClosed())
                                        System.out.println(client.getInetAddress() + ": Socket is closed");
                                    if (!client.isConnected())
                                        System.out.println(client.getInetAddress() +": Socket is not connected");
                                    if (client.isInputShutdown())
                                        System.out.println(client.getInetAddress() +": Socket input is shutdown");
                                }
                                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                                char[] targets = new char[1024];
                                int read = 0;
                                try {
                                    read = reader.read(targets);
                                } catch (IOException e) {
                                    System.out.println(client.getRemoteSocketAddress() +",客户端断开连接.");
                                    break;
                                }
                                if (targets.length > 0) {
                                    System.out.println(client.getRemoteSocketAddress() +" server accept message：" + String.valueOf(targets));
                                }
                            }
                    }
                }.setClient(accept);
                new Thread(runnable).start();
            }
        }
    }
}
